package com.atgouwu.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atgouwu.mall.cart.exception.CartExceptionHandler;
import com.atgouwu.mall.cart.feign.ProductFeignService;
import com.atgouwu.mall.cart.interceptor.MyHandlerInterceptor;
import com.atgouwu.mall.cart.service.CartService;
import com.atgouwu.mall.cart.to.UserInfoTo;
import com.atgouwu.mall.cart.vo.CartItemVo;
import com.atgouwu.mall.cart.vo.CartVo;
import com.atgouwu.mall.cart.vo.SkuInfoVo;
import com.atgouwu.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.atgouwu.mall.common.constant.CartConstant.CART_PREFIX;

@Slf4j
@Service("cartService")
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    //获取购物车(登录购物车+临时购物车)
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = MyHandlerInterceptor.toThreadLocal.get(); //获取当前用户(同一线程共享)
        if (userInfoTo.getUserId() != null) { //已登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId(); //登录购物车key
            String temptCartKey = CART_PREFIX + userInfoTo.getUserKey(); //临时购物车key
            List<CartItemVo> tempCartItems = getCartItems(temptCartKey); //获取临时购物车
            if (tempCartItems != null) { //临时购物车有数据进行合并
                for (CartItemVo item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                redisTemplate.delete(temptCartKey); //合并完清除临时购物车
            }
            List<CartItemVo> cartItems = getCartItems(cartKey); //获取购物车(包含合并的临时购物车和登录购物车数据)
            cartVo.setItems(cartItems);
        } else { //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey(); //"mall:cart:f7bc390d-1e5b-4d6e-91c5-87d8db7686b9"
            List<CartItemVo> cartItems = getCartItems(cartKey); //获取临时购物车里的所有购物项
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }

    //获取购物车里面的所有商品
    private List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0) {
            List<CartItemVo> cartItemVoStream = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItemVo cartItem = JSON.parseObject(str, CartItemVo.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItemVoStream;
        }
        return null;
    }

    //添加商品到购物车redis {"mall:cart:用户id或key": {"skuId": 购物项}}
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps(); //从redis获取购物车
        String productRedisValue = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(productRedisValue)) { //redis没有该商品就添加
            CartItemVo cartItemVo = new CartItemVo();
            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> { //(开启第一个异步任务)
                R productSkuInfo = productFeignService.getInfo(skuId); //远程查询当前要添加商品信息
                SkuInfoVo skuInfo = productSkuInfo.getData("data", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setSkuId(skuInfo.getSkuId());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setCount(num);
            }, executor);
            CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> { //开启第二个异步任务
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId); //远程查询skuAttrValues组合信息
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);
            CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrValuesFuture).get(); //等待所有异步任务全部完成
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson); //添加新商品到购物车redis
            return cartItemVo;
        } else { //redis有该商品,修改数量
            CartItemVo cartItemVo = JSON.parseObject(productRedisValue, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson); //修改redis的数据
            return cartItemVo;
        }
    }

    //从redis获取购物车
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = MyHandlerInterceptor.toThreadLocal.get(); //获取到当前用户信息
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId(); //登录购物车key(mall:cart:1)
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey(); //临时购物车key
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey); //获取购物车
        return operations;
    }

    //修改购物项数量
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItemVo cartItem = getCartItem(skuId); //查询购物车里的商品
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String redisValue = JSON.toJSONString(cartItem); //序列化
        cartOps.put(skuId.toString(), redisValue); //存入redis中
    }

    //查询购物车里的商品
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps(); //获取要操作的购物车信息
        String redisValue = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);
        return cartItemVo;
    }

    //删除购物项
    @Override
    public void deleteIdCartInfo(Integer skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    //查询当前用户购物车选中的商品项
    @Override
    public List<CartItemVo> getUserCartItems() {
        List<CartItemVo> cartItemVoList = new ArrayList<>();
        UserInfoTo userInfoTo = MyHandlerInterceptor.toThreadLocal.get(); //获取当前用户登录信息
        if (userInfoTo.getUserId() == null) { //用户未登录为null
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey); //获取所有的购物车项
            if (cartItems == null) {
                throw new CartExceptionHandler();
            }
            cartItemVoList = cartItems.stream().filter(items -> items.getCheck()).map(item -> { //筛选出选中的
                BigDecimal price = productFeignService.getPrice(item.getSkuId()); //查询数据库更新为最新价格
                item.setPrice(price);
                return item;
            }).collect(Collectors.toList());
        }
        return cartItemVoList;
    }

}
